package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"yzy4.15work/models"
)

type GoodController struct {
	beego.Controller
}

func (c *GoodController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var Goods []models.Good
	name := c.GetString("name")
	key := fmt.Sprintf("name:%s", name)
	JsonGet, _ := models.Rdb.Get(models.Ctx, key).Result()
	if JsonGet == "" {
		if models.DB.Where("name like ?", "%"+name+"%").Find(&Goods).Error != nil {
			c.Data["json"] = map[string]any{
				"Code": 500,
				"Msg":  "服务器繁忙",
			}
			c.ServeJSON()
			return
		}
		JsonSet, _ := json.Marshal(&Goods)
		models.Rdb.Set(models.Ctx, key, JsonSet, 0)
	} else {
		json.Unmarshal([]byte(JsonGet), &Goods)
	}

	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "查询成功",
		"Data": Goods,
	}
	c.ServeJSON()
}
func (c *GoodController) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var Goods models.Good
	Goods.Name = c.GetString("name")
	Goods.Description = c.GetString("des")
	Goods.Id, _ = c.GetInt("id")
	Goods.Price, _ = c.GetFloat("price")
	Goods.Stock, _ = c.GetInt("stock")
	key := fmt.Sprintf("goods:%s", Goods.Name)
	if models.DB.Updates(&Goods).Error != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	JsonSet, _ := json.Marshal(&Goods)
	if models.Rdb.Set(models.Ctx, key, JsonSet, 0).Err() != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "修改成功",
	}
	c.ServeJSON()
}
func (c *GoodController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var Goods models.Good
	Goods.Name = c.GetString("name")
	key := fmt.Sprintf("goods:%s", Goods.Name)
	if models.DB.Where("name = ?", Goods.Name).Delete(&Goods).Error != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	if models.Rdb.Del(models.Ctx, key, Goods.Name).Err() != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "删除成功",
	}
	c.ServeJSON()
}
